package com.oracle.sbdb.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.oracle.sbdb.bo.BugInfoBo;
import com.oracle.sbdb.servlet.model.BugInformation;
import com.oracle.sbdb.util.JSONUtility;

/**
 * Servlet implementation class SelectBugbyID
 */
@WebServlet("/selectBugbyID")
public class SelectBugbyID extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public SelectBugbyID() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String bugIDParameter = request.getParameter("bugID");
		String responseContent = selectBugbyID(bugIDParameter);
		PrintWriter out = response.getWriter();
		out.write(responseContent);
		out.flush();
		out.close();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		JSONObject requestJson = JSONUtility.getRequestString(request);
		String bugIDParameter = requestJson.getString("bugID");
		String responseContent = selectBugbyID(bugIDParameter);
		PrintWriter out = response.getWriter();
		out.write(responseContent);
		out.flush();
		out.close();
	}

	private String selectBugbyID(String bugIDString){
		BugInformation bugInformation = null;
		try{
			if(bugIDString != null){
				int bugID = -1;
				
				try{
					bugID = Integer.parseInt(bugIDString.trim());
				}catch(Exception e){
					e.printStackTrace();
				}
				if(bugID >= 0){
					BugInfoBo bugInfoBo = BugInfoBo.INSTANCE;
					bugInformation = bugInfoBo.selectbyID(bugID);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		JSONObject res = new JSONObject();
		res.put("Status", bugInformation == null ? "Fail" : "Success");
		res.put("Result", bugInformation);
		return res.toString();
	}
}
